package com.example.mybatisplusproject.endecrypt;

import com.example.mybatisplusproject.annotation.EncryptDecryptField;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.springframework.stereotype.Component;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.IOException;
import java.lang.reflect.Field;
import java.nio.charset.StandardCharsets;

/**
 * @author zls
 * @date 2021/8/1 9:10 下午
 */
@Component
@Slf4j
public class EncryptDecryptImpl implements IEncryptDecrypt{
    @Override
    public void encrypt(Field[] fields, Object parameterObject) throws IllegalAccessException {
        log.info("开始加密....");
        for (Field field : fields) {
            if(field.getAnnotation(EncryptDecryptField.class) != null) {
                log.info("遇到需加密字段，{}",field.getName());
                field.setAccessible(true);
                String paramValue = (String)field.get(parameterObject);
                String encryptValue = Base64.encodeBase64String(paramValue.getBytes(StandardCharsets.UTF_8));
                field.set(parameterObject,encryptValue);
                log.info("加密字段{}完成，加密结果为：{}",field.getName(),encryptValue);
            }
        }
    }

    @Override
    public void decrypt(Object parameterObject) throws IllegalAccessException {
        log.info("开始解密....");
        Field[] fields = parameterObject.getClass().getDeclaredFields();
        for (Field field : fields) {
            if(field.getAnnotation(EncryptDecryptField.class) != null) {
                log.info("遇到需解密字段，{}",field.getName());
                field.setAccessible(true);
                String paramValue = (String)field.get(parameterObject);
                byte[] bytes = Base64.decodeBase64(paramValue);
                String encryptValue = new String(bytes);
                field.set(parameterObject, encryptValue);
                log.info("解密字段{}完成，原加密结果为：{}，解密结果为：{}",field.getName(), paramValue, encryptValue);
            }
        }
    }
}
